package com.ruoyi.web.controller.members;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.MembersConstant;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.enums.MembersStatus;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.flowable.common.enums.FlowComment;
import com.ruoyi.flowable.service.ISysFormService;
import com.ruoyi.system.domain.ActReProcdef;
import com.ruoyi.system.domain.SysForm;
import com.ruoyi.system.service.IActReProcdefService;
import com.ruoyi.common.core.domain.entity.SysUser;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.members.domain.SysMembers;
import com.ruoyi.members.service.ISysMembersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 会员管理（仅查询/修改/删除，不含新增）
 */
@RestController
@RequestMapping("/system/members/management")
public class SysMembersManageController extends BaseController {

    @Autowired
    private ISysMembersService sysMembersService;

    @Autowired
    private IActReProcdefService actReProcdefService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ISysFormService sysFormService;

    /**
     * 会员列表（仅“是会员”：members_is_status = 0）
     */
    @GetMapping("/list")
    public TableDataInfo list(SysMembers sysMembers) {
        LambdaQueryWrapper<SysMembers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysMembers::getMembersIsStatus, MembersConstant.IS_MEMBERS);
        if (StringUtils.isNotNull(sysMembers.getMembersName())) {
            wrapper.like(SysMembers::getMembersName, sysMembers.getMembersName());
        }
        if (StringUtils.isNotNull(sysMembers.getMembersNum())) {
            wrapper.eq(SysMembers::getMembersNum, sysMembers.getMembersNum());
        }
        if (StringUtils.isNotNull(sysMembers.getMembersTel())) {
            wrapper.eq(SysMembers::getMembersTel, sysMembers.getMembersTel());
        }
        if (StringUtils.isNotNull(sysMembers.getSchool())) {
            wrapper.like(SysMembers::getSchool, sysMembers.getSchool());
        }
        Page<SysMembers> pageReq = new Page<>(sysMembers.getPageNum(), sysMembers.getPageSize());
        Page<SysMembers> page = sysMembersService.page(pageReq, wrapper);
        return new TableDataInfo(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    /** 导出 */
    @PreAuthorize("@ss.hasPermi('members:management:export')")
    @Log(title = "会员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysMembers sysMembers) {
        LambdaQueryWrapper<SysMembers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysMembers::getMembersIsStatus, MembersConstant.IS_MEMBERS);
        if (StringUtils.isNotNull(sysMembers.getMembersName())) {
            wrapper.like(SysMembers::getMembersName, sysMembers.getMembersName());
        }
        if (StringUtils.isNotNull(sysMembers.getMembersNum())) {
            wrapper.eq(SysMembers::getMembersNum, sysMembers.getMembersNum());
        }
        if (StringUtils.isNotNull(sysMembers.getMembersTel())) {
            wrapper.eq(SysMembers::getMembersTel, sysMembers.getMembersTel());
        }
        if (StringUtils.isNotNull(sysMembers.getSchool())) {
            wrapper.like(SysMembers::getSchool, sysMembers.getSchool());
        }
        List<SysMembers> list = sysMembersService.list(wrapper);
        ExcelUtil<SysMembers> util = new ExcelUtil<>(SysMembers.class);
        util.exportExcel(response, list, "会员数据", "会员信息统计表");
    }

    /** 详情 */
    @GetMapping(value = "/{membersId}")
    public AjaxResult getInfo(@PathVariable("membersId") Long membersId) {
        return success(sysMembersService.getById(membersId));
    }

    /** 修改 */
    @PreAuthorize("@ss.hasPermi('members:management:edit')")
    @Log(title = "会员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysMembers sysMembers) {
        return toAjax(sysMembersService.updateById(sysMembers));
    }

    /** 删除 */
    @PreAuthorize("@ss.hasPermi('members:management:remove')")
    @Log(title = "会员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{membersIds}")
    public AjaxResult remove(@PathVariable Long[] membersIds) {
        return toAjax(sysMembersService.removeByIds(java.util.Arrays.asList(membersIds)) ? 1 : 0);
    }

    /**
     * 会员转会申请（发起审批流）
     * 流程名称：申请转会
     */
    @PostMapping("/transferFlowable")
    public AjaxResult transferApply(@RequestBody SysMembers sysMember) {
        // 先保存修改（如 deptId 转入目标部门）
        boolean updated = sysMembersService.updateById(sysMember);
        if (!updated) {
            return error(MembersStatus.OPERATE_FAIL.getInfo());
        }

        try {
            sysMember.setCreateBy(getUsername());
            // 查询“申请转会”流程定义，按版本倒序取最新
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ActReProcdef> query = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            query.eq(ActReProcdef::getName, "转入工会");
            query.orderByDesc(ActReProcdef::getVersion);
            java.util.List<ActReProcdef> list = actReProcdefService.list(query);

            if (list != null && !list.isEmpty()) {
                // 启动流程实例
                java.util.HashMap<String, Object> variables = new java.util.HashMap<>();
                variables.put("commonClass", sysMember);
                // 绑定表单（如有）
                SysForm form = new SysForm();
                form.setFormName("转会表单");
                java.util.List<SysForm> forms = sysFormService.selectSysFormList(form);
                if (forms.size() > 0) {
                    forms.sort(java.util.Comparator.comparing(SysForm::getFormId).reversed());
                    variables.put("formJson", forms.get(0).getFormContent());
                }

                SysUser user = SecurityUtils.getLoginUser().getUser();
                identityService.setAuthenticatedUserId(user.getUserId().toString());
                variables.put(ProcessConstants.PROCESS_INITIATOR, user.getUserId());

                ProcessInstance processInstance = runtimeService.startProcessInstanceById(list.get(0).getId(), variables);
                Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
                if (task != null) {
                    taskService.addComment(task.getId(), processInstance.getProcessInstanceId(), FlowComment.NORMAL.getType(), user.getNickName() + "发起转会流程申请");
                    taskService.complete(task.getId(), variables);
                }
            } else {
                // 无流程定义则仅保存数据
                // 可按需返回提示
            }
            return success("转会申请提交成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error("转会申请提交失败");
    }

    /**
     * 会员退会申请（发起审批流）
     * 流程名称：申请退会
     */
    @PostMapping("/quitFlowable")
    public AjaxResult quitApply(@RequestBody SysMembers sysMember) {
        // 保存变更（若前端携带了备注等）
        boolean updated = sysMembersService.updateById(sysMember);
        if (!updated) {
            return error(MembersStatus.OPERATE_FAIL.getInfo());
        }

        try {
            sysMember.setCreateBy(getUsername());
            // 查询“申请退会”流程定义
            LambdaQueryWrapper<ActReProcdef> qw = new LambdaQueryWrapper<>();
            qw.eq(ActReProcdef::getName, "申请退回流程");
            qw.orderByDesc(ActReProcdef::getVersion);
            List<ActReProcdef> list = actReProcdefService.list(qw);

            if (list != null && !list.isEmpty()) {
                java.util.HashMap<String, Object> variables = new java.util.HashMap<>();
                variables.put("commonClass", sysMember);
                // 绑定表单
                SysForm form = new SysForm();
                form.setFormName("退会表单");
                java.util.List<SysForm> forms = sysFormService.selectSysFormList(form);
                if (forms.size() > 0) {
                    forms.sort(java.util.Comparator.comparing(SysForm::getFormId).reversed());
                    variables.put("formJson", forms.get(0).getFormContent());
                }

                SysUser user = SecurityUtils.getLoginUser().getUser();
                identityService.setAuthenticatedUserId(user.getUserId().toString());
                variables.put(ProcessConstants.PROCESS_INITIATOR, user.getUserId());

                ProcessInstance pi = runtimeService.startProcessInstanceById(list.get(0).getId(), variables);
                Task task = taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
                if (task != null) {
                    taskService.addComment(task.getId(), pi.getProcessInstanceId(), FlowComment.NORMAL.getType(), user.getNickName() + "发起退会流程申请");
                    taskService.complete(task.getId(), variables);
                }
            }
            return success("退会申请提交成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error("退会申请提交失败");
    }
}


